<?php
/**
 * 行情数据
 */
namespace quote\service;

use common\service\CommonService;
use herosphp\core\Loader;
use herosphp\core\Log;
use herosphp\bean\Beans;
use api\utils\SaasApiClient;
use herosphp\exception\HeroException;

class QuoteDataService extends CommonService
{
    //维护的几大品类
    public $productNameByHotArr = array('PVC', 'PP', 'PET', 'LLDPE', 'ABS', 'HIPS', 'HDPE', 'PC', 'GPPS');

    public function __construct()
    {
        parent::__construct('quoteData');
    }


    public function getProductNameByHotArr()
    {

        return $this->productNameByHotArr;
    }



    /**
     *  判断关键词是否在牌号数据中
     * @param $product_name
     * @param $brand_name
     */
    public function searchPBFromBrand($k1, $k2)
    {
        $url = "api/brand/searchBrandByTwoKeyword";
        $result = SaasApiClient::send($url, array('k1' => $k1, 'k2' => $k2));
        if ($result->isSucess()) {
            $arr = $result->getData();
        } else {
            $arr = array();
            error_log($result->getMessage());
        }

        return $arr;
    }


    /**
     * 获取行情数据
     * @param $pagesize
     * @param $page
     * @param $searchArr
     * @return mixed
     */
    public function getList($pagesize, $page, $searchArr)
    {

        $conditions = array();

        $conditions['brand_name'] = $searchArr['brand_name'];

        if ($searchArr['addtime_s'] !== '' && $searchArr['addtime_s'] !== NULL) {
            $conditions['addtime'] = array();
            $conditions['addtime']['>'] = $searchArr['addtime_s'] . ' 00:00:00';
        }

        if ($searchArr['addtime_e'] !== '' && $searchArr['addtime_e'] !== NULL) {
            if (!$conditions['addtime']) {
                $conditions['addtime'] = array();
            }
            $conditions['addtime']['<='] = $searchArr['addtime_e'] . ' 23:59:59';
        }

        $service = Beans::get('quote.data.service');

        $result['total'] = $service->count($conditions);

        $result['items'] = $service->getItems($conditions, '', array('addtime' => -1), array($page, $pagesize));

        return $result;

    }

    /**
     * 向行情增加数据
     *
     * @param $data
     * @return mixed
     */
    public function addOrUpdateQuoteData( $data ){
        $copy = $data['copy'];
        $new = $data['new'];
        $has_quote = $data['has_quote'];
        $time = date('Y-m-d H:i:s');
        $date = date('Y-m-d');
        if( $has_quote ){
            //复制今天数据
            $conditions = array(
                'adddate' => $date,
                'is_delete' => 0
            );
        }else{
            //复制昨天数据
            $conditions = array(
                'adddate' => date('Y-m-d',time()-86400),
                'is_delete' => 0
            );
        }

        $items = parent::getItems($conditions);
        $this -> beginTransaction();
        $tmp = [];
        if( $has_quote ){
            foreach ($items as $value ){
                $tmp[] = $value['pfb'];
                foreach ($copy as $cv){
                    if( $value['pfb'] == $cv['pfb'] ) {
                        $value['price'] = $cv['price'];
                        $value['edittime'] = $time;
                        try {
                            $this->update($value,$value['id']);
                        } catch (HeroException $e) {
                            Log::error($e->getMessage());
                            $this->rollback();
                            return false;
                        }
                    }
                }
            }
        } else {
            foreach ($items as $value) {
                $tmp[] = $value['pfb'];
                foreach ($copy as $cv) {
                    if ($value['pfb'] == $cv['pfb']) {
                        $value['price'] = $cv['price'];
                        $value['manager_id'] = $cv['manager_id'];
                        $value['views'] = 0;
                        $value['addtime'] = $time;
                        $value['edittime'] = $time;
                        $value['adddate'] = $date;
                        try {
                            unset($value['id']);
                            $this->add($value);
                        } catch (HeroException $e) {
                            Log::error($e->getMessage());
                            $this->rollback();
                            return false;
                        }
                    }
                }
            }
        }

        //新增数据
        foreach ($new as $nv){
            if( in_array($nv['pfb'],$tmp) ){
                /*$value['price'] = $cv['price'];
                $value['edittime'] = $time;
                try {
                    $this->update($value,$value['id']);
                } catch (HeroException $e) {
                    Log::error($e->getMessage());
                    $this->rollback();
                    return false;
                }*/
            }else {
                $nv['addtime'] = $time;
                $nv['edittime'] = $time;
                $nv['adddate'] = $date;
                try {
                    $this->add($nv);
                } catch (HeroException $e) {
                    Log::error($e->getMessage());
                    $this->rollback();
                    return false;
                }
            }
        }


        $this -> commit();
        return true;

    }

    public function getDataList($conditions,$order, $limit){

        $where = "";
        $where .= $conditions;
        $offset = ($limit[0] - 1)*$limit[1];
        if( $limit ){
            $limit = "limit {$offset},{$limit[1]}";
        }
        //$date = date('Y-m-d');
        //$sql = "select a.*,b.price as `yesterday_price` ,b.adddate from quote_data a left join quote_data b on b.adddate=a.adddate-1 where 1=1 and a.is_delete=0 {$where} order by {$order} limit {$limit[0]},{$limit[1]}";
        $sql = "select  b.price as `yesterday_price` ,b.adddate ,a.* from quote_data a left join quote_data b on b.adddate=FROM_UNIXTIME(unix_timestamp(a.adddate)-86400, '%Y-%m-%d') And a.pfb=b.pfb where 1=1 and a.is_delete=0 {$where} order by {$order} {$limit}";
        //Log::error($sql);
        $items = $this -> getDB()->query($sql);
        $totalSql = "select count(*) as `count` from quote_data a left join quote_data b on b.adddate=FROM_UNIXTIME(unix_timestamp(a.adddate)-86400, '%Y-%m-%d') And a.pfb=b.pfb where 1=1 and a.is_delete=0 {$where} ";
        $total = $this -> getDB()->query($totalSql);
        //return $items;
        if( $items ){
            $managerService = Beans::get('admin.manager.service');
            $ids = [];
            foreach ( $items as $key => $value ){
                if( $value['yesterday_price'] ){
                    $items[$key]['is_diff'] = true;
                    $items[$key]['difference'] = round($value['price']-$value['yesterday_price'],2);
                }else{
                    $items[$key]['is_diff'] = false;
                    $items[$key]['difference'] =0;
                }
                $ids[] = $value['manager_id'];
            }
            $managerItems = $managerService -> getItems(['id'=>['$in'=>$ids]]);
            foreach ($managerItems as $mv){
                foreach ($items as $key => $value) {
                    if ($mv['id'] == $value['manager_id']) {
                        $items[$key]['manager_name'] = $mv['name'];
                    }
                }
            }
        }
        return [
            'items'=>$items,
            'total'=>$total[0]['count']
        ];

    }
    /**
     * 封装图表数据
     * @param $trendItems 图表原始数据
     * @param $x_span_start 横轴跨度开始
     * @param $x_span_end 横轴跨度结束
     * @return array
     */
    public function getChartData($trendItems, $x_span_start, $x_span_end)
    {
        //获取x轴量
        $x_diff=strtotime($x_span_end) - strtotime($x_span_start);
        //x轴跨度
        $xs = range(0,$x_diff/ (3600 * 24));

        //如果x轴跨度大于300，则返回,太长不予渲染
        if(count($xs)>300){

            return false;
        }

        $x_arr = array();//x轴
        $y_arr = array();//y轴

        foreach ($xs as $x) {

            $mydate = date('Y-m-d', strtotime($x_span_start) + (3600 * 24) * ($x));

            $mydateArr = explode('-', $mydate);

            $x_arr []= "[$x,gd(" . $mydateArr[0] . ", " . ($mydateArr[1]) . ", " . ($mydateArr[2]) . ")]";

            $price = $this->getPrice($trendItems, $mydate);

            if ($price) {

                $y_arr []= "[$x," . $price . "]";

            } else {

                $y_arr []= "[$x,0]";

            }
        }

        return array('x_arr' => join(',',$x_arr), 'y_arr' => join(',',$y_arr));


    }
    //获取价格
    private function getPrice($trendItems, $date)
    {

        foreach ($trendItems as $k => $item) {
            if ($item['adddate'] == $date) {

                return $item['price'];
            }
        }

        return null;
    }

}